package com.yimi.appstore.download2;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Currency;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import com.yimi.appstore.YimiApplication;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

public class FileService {
	private DBOpenHelper openHelper;

	public FileService(Context context) {
		openHelper = new DBOpenHelper(context);
	}

	/**
	 * 根据url获取下载记录
	 * 
	 * @param path
	 * @return
	 */
	public Map<Integer, Long> getData(String path) {
		SQLiteDatabase db = null;
		Cursor cursor = null;
		Map<Integer, Long> data = new HashMap<Integer, Long>();
		try {
			db = openHelper.getReadableDatabase();
			cursor = db
					.rawQuery("select threadid, downlength from filedownlog where downpath=?", new String[] { path });
			while (cursor.moveToNext()) {
				data.put(cursor.getInt(0), cursor.getLong(1));
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (cursor != null)
				cursor.close();
			if (db != null)
				db.close();
		}
		return data;
	}

	/**
	 * 保存正在下载记录
	 * 
	 * @param downloadUrl
	 * @param map
	 * @param totleSize
	 * @param appName
	 * @param iconUrl
	 * @param localpath
	 * @param mediaType
	 */
	public void save(String downloadUrl, Map<Integer, Long> map, Long totleSize, String resource, String iconUrl,
			String localpath, String mediaType) {// int threadid,
		if (!isExitUrl(downloadUrl)) {
			SQLiteDatabase db = openHelper.getWritableDatabase();
			db.beginTransaction();
			try {
				for (Map.Entry<Integer, Long> entry : map.entrySet()) {
					db.execSQL(
							"insert into filedownlog(resource ,iconurl ,downpath,localpath ,threadid, downlength , totlesize , mediatype) values(?,?,?,?,?,?,?,?)",
							new Object[] { resource, iconUrl, downloadUrl, localpath, entry.getKey(), entry.getValue(),
									totleSize, mediaType });
				}
				db.setTransactionSuccessful();
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				db.endTransaction();
				db.close();
			}
		}
	}

	/**
	 * 保存完成下载记录
	 * @param resource
	 * @param iconUrl
	 * @param downloadUrl
	 * @param localpath
	 * @param mediaType
	 * @param totleSize
	 */
	public void saveDownloadHistory(String resource, String iconUrl, String downloadUrl, String localpath,
			String mediaType, Long totleSize) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
		String createTime = sdf.format(new Date(System.currentTimeMillis()));
		SQLiteDatabase db = openHelper.getWritableDatabase();
		db.beginTransaction();
		try {
			db.execSQL(
					"insert into filedownhistory(resource,iconurl,downpath,localpath,mediatype,createtime,totlesize) values(?,?,?,?,?,?,?)",
					new Object[] { resource, iconUrl, downloadUrl, localpath ,mediaType, createTime, totleSize });
			db.setTransactionSuccessful();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			db.endTransaction();
			db.close();
		}
	}

	/**
	 * 是否存在下载记录
	 * @param path
	 * @return
	 */
	public synchronized boolean isExitUrl(String path) {
		boolean result = false;
		SQLiteDatabase db = null;
		Cursor cursor = null;
		try {
			db = openHelper.getReadableDatabase();
			cursor = db
					.rawQuery("select threadid, downlength from filedownlog where downpath=?", new String[] { path });

			while (cursor.moveToNext()) {
				result = true;
			}
		} catch (Exception e) {
			// TODO: handle exception
		} finally {
			if (cursor != null)
				cursor.close();
			if (db != null)
				db.close();
		}
		return result;
	}

	/**
	 * 更新下载
	 * 
	 * @param path
	 * @param map
	 * @param totlesize
	 */
	public synchronized void update(String path, Map<Integer, Long> map, long totlesize) {
		SQLiteDatabase db = openHelper.getWritableDatabase();
		db.beginTransaction();

		try {
			for (Map.Entry<Integer, Long> entry : map.entrySet()) {
				db.execSQL("update filedownlog set downlength=? , totlesize = ? where downpath=? and threadid=?",
						new Object[] { entry.getValue(), totlesize, path, entry.getKey() });
			}

			db.setTransactionSuccessful();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			db.endTransaction();
			db.close();
		}

	}

	/**
	 * 删除正在下载记录
	 * 
	 * @param path
	 */
	public synchronized void delete(String path) {
		SQLiteDatabase db = openHelper.getWritableDatabase();
		db.execSQL("delete from filedownlog where downpath=?", new Object[] { path });
		db.close();
	}

	/**
	 * 获取所有下载记录
	 * 
	 * @param context
	 * @return
	 */
	public ArrayList<DownloadJob> getAllDownload(Context context) {
		ArrayList<DownloadJob> result = new ArrayList<DownloadJob>();
		SQLiteDatabase db = null;
		Cursor cursor = null;
		try {
			db = openHelper.getReadableDatabase();
			cursor = db
					.rawQuery(
							"select resource , iconurl, totlesize , downpath , sum( downlength) ,localpath from filedownlog group by downpath",
							null);
			while (cursor.moveToNext()) {
				DownloadEntity de = new DownloadEntity();
				de.setResource((cursor.getString(0)));
				de.setIconUrl(cursor.getString(1));
				de.setTotalBytes(cursor.getLong(2));
				de.setUrl(cursor.getString(3));
				de.setCurrentBytes(cursor.getLong(4));
				de.setLocalPath(cursor.getString(5));
				DownloadJob job = new DownloadJob(de, context);
				job.setJobStatus(DownloadManager.STATE_PAUSE);
				result.add(job);
				YimiApplication.downloadingList.add(de.getUrl());
			}
		} catch (Exception e) {
			// TODO: handle exception
		} finally {
			if (cursor != null)
				cursor.close();
			if (db != null)
				db.close();
		}
		return result;
	}

	/**
	 * 获取所有下载完成历史
	 * 
	 * @return ArrayList<DownloadEntry>
	 */
	public ArrayList<DownloadEntity> getAllDownloadHistory() {
		ArrayList<DownloadEntity> result = new ArrayList<DownloadEntity>();
		SQLiteDatabase db = null;
		Cursor cursor = null;
		try {
			db = openHelper.getReadableDatabase();
			cursor = db.rawQuery("select resource , iconurl, totlesize , downpath ,localpath from filedownhistory",
					null);
			while (cursor.moveToNext()) {
				DownloadEntity de = new DownloadEntity();
				de.setResource((cursor.getString(0)));
				de.setIconUrl(cursor.getString(1));
				de.setTotalBytes(cursor.getLong(2));
				de.setUrl(cursor.getString(3));
				de.setLocalPath(cursor.getString(4));
				result.add(de);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (cursor != null)
				cursor.close();
			if (db != null)
				db.close();
		}
		return result;
	}

	/**
	 * 删除完成下载记录
	 * 
	 * @param url
	 */
	public void deleteDownloadHistory(String url) {
		SQLiteDatabase db = openHelper.getWritableDatabase();
		db.execSQL("delete from filedownhistory where downpath=?", new Object[] { url });
		db.close();
	}
}
